;(function($) {
    $.fn.load_chart = function(chart_type, opts, post_data)
    {
        var options = $.extend({}, $.fn.load_chart.defaults, opts);
        var $$ = $(this);
        var load_bar_chart = function() {
            var cube = options.cube,
                chartConfig = options.chart,
                myChart = echarts.init($$[0], "default");
            var option = {
                title: {
                },
                tooltip: {
                    trigger: "axis",
                    show: true
                },
                grid: {
                    left: chartConfig["grid.left"],
                    right: chartConfig["grid.right"],
                    containLabel: chartConfig["grid.containLabel"]
                },
                legend: {
                    x: 'center',
                    data: [], 
                    selected: [] 
                },
                toolbox: {
                    show : chartConfig["toolbox.show"],
                    orient : chartConfig["toolbox.orient"],
                    x: 'right',
                    y: 'center',
                    feature : {
                        mark : {show: true},
                        dataView : {show: true, readOnly: false},
                        magicType : {show: true, type: ['line', 'bar', 'stack', 'tiled']},
                        restore : {show: true},
                        saveAsImage : {show: true}
                    }
                },
                xAxis: [
                    {
                        type : chartConfig["xAxis.type"],
                        data : [],
                        axisLabel: {
                            formatter: chartConfig["xAxis.axisLabel.formatter"]
                        }
                    }
                ],
                yAxis: [
                    {
                        name: chartConfig["yAxis.0.name"],
                        type: chartConfig["yAxis.0.type"],
                        data: [],
                        axisLabel: {
                            formatter: chartConfig["yAxis.0.axisLabel_formatter"]
                        }
                    }
                ],
                series: []
            };
            if (chartConfig["yAxis.1.show"] === true) {
                option.yAxis.push(
                     {
                        name: chartConfig["yAxis.1.name"],
                        type: chartConfig["yAxis.1.type"],
                        data: [],
　　                    splitLine:{
　　                    　　show: false
　　                    },
                        axisLabel: {
                            formatter: chartConfig["yAxis.1.axisLabel_formatter"]
                        }
                    }
                );
            }
            if (chartConfig["title.show"] === true) {
                option.title.text = chartConfig["title.text"];
            }
            $.ajax({
                type: "POST",
                url: "/report/cubeship/getdata/",
                timeout: 300000,
                data: post_data,
                beforeSend: function(xhr, settings) {
                    if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                        xhr.setRequestHeader("X-CSRFToken", csrftoken);
                    }
                    myChart.showLoading({
                        text: 'loading...'
                    });
                },
                success: function(result){
                    option.xAxis[0].data = result.xaxis;
                    option.legend.data = result.legend;
                    $.map(result.cells, function (value, key) {
                        var type = "bar",
                            yAxisIndex = 0,
                            stack = "";
                        if (key in result.agg_config_dict){
                            if (result.agg_config_dict[key].chart_type != "") {
                                var type = result.agg_config_dict[key].chart_type;
                            }
                            if(chartConfig["yAxis.1.show"] === true) {
                                yAxisIndex = result.agg_config_dict[key].yaxis_index == "right" ? 1:0;
                            }
                            var stack = result.agg_config_dict[key].stack;
                        }
                        option.series.push({
                            name: key, 
                            type: type, 
                            yAxisIndex: yAxisIndex,
                            stack: stack,
                            data: value, 
                        });
                    });
                    myChart.resize();
                    myChart.hideLoading();
                    myChart.setOption(option); 
                }
            });
        };

        var load_line_chart = function() {
            var cube = options.cube,
                chartConfig = options.chart,
                myChart = echarts.init($$[0], "default");
            var option = {
                title: {
                },
                tooltip: {
                    trigger: "axis",
                    show: true
                },
                grid: {
                    left: chartConfig["grid.left"],
                    right: chartConfig["grid.right"],
                    containLabel: chartConfig["grid.containLabel"]
                },
                legend: {
                    x: 'center',
                    data: [], 
                    selected: [] 
                },
                toolbox: {
                    show : chartConfig["toolbox.show"],
                    orient : chartConfig["toolbox.orient"],
                    x: 'right',
                    y: 'center',
                    feature : {
                        mark : {show: true},
                        dataView : {show: true, readOnly: false},
                        magicType : {show: true, type: ['line', 'bar', 'stack', 'tiled']},
                        restore : {show: true},
                        saveAsImage : {show: true}
                    }
                },
                xAxis: [
                    {
                        type : chartConfig["xAxis.type"],
                        data : [],
                        axisLabel: {
                            formatter: chartConfig["xAxis.axisLabel.formatter"]
                        }
                    }
                ],
                yAxis: [
                    {
                        name: chartConfig["yAxis.0.name"],
                        type: chartConfig["yAxis.0.type"],
                        data: [],
                        axisLabel: {
                            formatter: chartConfig["yAxis.0.axisLabel_formatter"]
                        }
                    }
                ],
                series: []
            };
            if (chartConfig["yAxis.1.show"] === true) {
                option.yAxis.push(
                     {
                        name: chartConfig["yAxis.1.name"],
                        type: chartConfig["yAxis.1.type"],
                        data: [],
　　                    splitLine:{
　　                    　　show: false
　　                    },
                        axisLabel: {
                            formatter: chartConfig["yAxis.1.axisLabel_formatter"]
                        }
                    }
                );
            }
            if (chartConfig["title.show"] === true) {
                option.title.text = chartConfig["title.text"];
            }
            $.ajax({
                type: "POST",
                url: "/report/cubeship/getdata/",
                timeout: 300000,
                data: post_data,
                dataType: "json",
                beforeSend: function(xhr, settings) {
                    if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                        xhr.setRequestHeader("X-CSRFToken", csrftoken);
                    }
                    myChart.showLoading({
                        text: 'loading...'
                    });
                },
                success: function(result){
                    option.xAxis[0].data = result.xaxis;
                    option.legend.data = result.legend;
                    $.map(result.cells, function (value, key) {
                        var type = "line",
                            yAxisIndex = 0,
                            stack = "";
                        if (key in result.agg_config_dict){
                            if (result.agg_config_dict[key].chart_type != "") {
                                var type = result.agg_config_dict[key].chart_type;
                            }
                            if(chartConfig["yAxis.1.show"] === true) {
                                yAxisIndex = result.agg_config_dict[key].yaxis_index == "right" ? 1:0;
                            }
                            var stack = result.agg_config_dict[key].stack;
                        }
                        option.series.push({
                            name: key, 
                            type: type, 
                            yAxisIndex: yAxisIndex,
                            stack: stack,
                            data: value, 
                        });
                    });
                    myChart.resize();
                    myChart.hideLoading();
                    myChart.setOption(option); 
                }
            });
        };
        var load_pie_chart = function() {
            var cube = options.cube,
                chartConfig = options.chart,
                myChart = echarts.init($$[0], "default");
            var option = {
                title: {
                },
                tooltip: {
                    show: true,
                    trigger: 'item',
                    formatter: "{a} <br/>{b} : {c} ({d}%)"
                },
                legend: {
                    orient : chartConfig["legend.orient"],
                    x : 'left',
                    y : 'center',
                    data: [], 
                    selected: {}
                },
                toolbox: {
                    show : chartConfig["toolbox.show"],
                    orient : chartConfig["toolbox.orient"],
                    x: 'right',
                    y: 'center',
                    feature : {
                        mark : {show: true},
                        dataView : {show: true, readOnly: false},
                        magicType : {
                            show: true, 
                            type: ['pie', 'funnel']
                        },
                        restore : {show: true},
                        saveAsImage : {show: true}
                    }
                },
                calculable : true,
                series: [{type: 'pie', radius: '55%', center: ['50%', '50%'], data: []}]
            };
            if (chartConfig["title.show"] === true) {
                option.title.text = chartConfig["title.text"];
            }
            $.ajax({
                type: "POST",
                url: "/report/cubeship/getdata/",
                timeout: 300000,
                data: post_data,
                beforeSend: function(xhr, settings) {
                    if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                        xhr.setRequestHeader("X-CSRFToken", csrftoken);
                    }
                    myChart.showLoading({
                        text: 'loading...'
                    });
                },
                success: function(result){
                    option.legend.data = result.legend;
                    $.map(result.cells, function (value, key) {
                        option.series[0].data.push({
                            name: key, 
                            value: value 
                        });
                    });
                    myChart.resize();
                    myChart.hideLoading();
                    myChart.setOption(option); 
                }
            });
        };

        var load_datatables = function() {
            var post_dict = jQuery.deparam(post_data),
                table = document.createElement('table'),
                chartConfig = options.chart;
            table.className = "table table-striped no-footer";
            table.id = "preview_datatables";
            $$.append(table);
            var aoColumns = [];
            for (var i=0;i<options.drilldowns.length;i++){
                var label = options.name_label_dict[options.drilldowns[i].drilldown];
                aoColumns.push({sTitle: label});
            }
            for (var i=0;i<options.aggregates.length;i++){
                var label = options.name_label_dict[options.aggregates[i].aggregate];
                aoColumns.push({sTitle: label});
            }

            var oTable = $(table).dataTable({
                bFilter: false,
                bSort: true,
                aaSorting: [],
                bAutoWidth: true,
                bStateSave: false,
                bServerSide: true,
                bDeferRender: true, 
                bPaginate: true,
                bDestroy: true,
                buttons: [
                    {
                        text: 'Reload',
                        action: function ( e, dt, node, config ) {
                            dt.ajax.reload();
                        }
                    }
                ],
                aoColumns: aoColumns,
                sAjaxSource: "/report/cubeship/getdata/",
                fnServerData: function ( sSource, aoData, fnCallback ) {  
                    $.ajax({  
                        dataType: 'json',  
                        type: "POST",  
                        url: sSource,  
                        data: aoData,  
                        success: function(json) {
                            fnCallback(json);
                        },  
                        timeout: 300000
                    });
                }, 
                fnServerParams: function (aoData) {
                    $.each(post_dict, function(key, value){
                        aoData.push({name: key, value: value});
                    });
                },
                sScrollY: chartConfig["form.sScrollY"],
                iDisplayLength: chartConfig["form.iDisplayLength"],
                bScrollCollapse: false,
                scroller: {
                    loadingIndicator: true,
                    displayBuffer: 20,
                    boundaryScale: 0.9,
                    serverWait: 3000
                },
                language: {
                    emptyTable: "糟糕，没有匹配的数据项..."
                }
            });

            $(window).bind('resize', function () {
                oTable.fnAdjustColumnSizing();
            });

            // oTable.fnReloadAjax();

        };







        var load_scatter_chart = function() {
            var cube = options.cube,
                chartConfig = options.chart,
                myChart = echarts.init($$[0], "default");
            var option = {
                title: {
                },
                tooltip: {
                    trigger: "axis",
                    show: true
                },
                grid: {
                    left: chartConfig["grid.left"],
                    right: chartConfig["grid.right"],
                    containLabel: chartConfig["grid.containLabel"]
                },
                legend: {
                    x: 'center',
                    data: [], 
                    selected: [] 
                },
                toolbox: {
                    show : chartConfig["toolbox.show"],
                    orient : chartConfig["toolbox.orient"],
                    x: 'right',
                    y: 'center',
                    feature : {
                        mark : {show: true},
                        dataView : {show: true, readOnly: false},
                        magicType : {show: true, type: ['line', 'bar', 'stack', 'tiled']},
                        restore : {show: true},
                        saveAsImage : {show: true}
                    }
                },
                xAxis: [
                    {
                        type : chartConfig["xAxis.type"],
                        data : [],
                        axisLabel: {
                            formatter: chartConfig["xAxis.axisLabel.formatter"]
                        }
                    }
                ],
                yAxis: [
                    {
                        type : chartConfig["yAxis.type"],
                        scale:true,
                        axisLabel : {
                            formatter: chartConfig["yAxis.axisLabel.formatter"]
                        },
                        splitLine: {
                            show: false
                        }
                    }
                ],
                series: []
            };
            if (chartConfig["title.show"] === true) {
                option.title.text = chartConfig["title.text"];
            }
            $.ajax({
                type: "POST",
                url: "/report/cubeship/getdata/",
                timeout: 300000,
                data: post_data,
                dataType: "json",
                beforeSend: function(xhr, settings) {
                    if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                        xhr.setRequestHeader("X-CSRFToken", csrftoken);
                    }
                    myChart.showLoading({
                        text: 'loading...'
                    });
                },
                success: function(result){
                    option.xAxis[0].data = result.xaxis;
                    option.legend.data = result.legend;
                    $.map(result.cells, function (value, key) {
                        option.series.push({
                            name: key, 
                            type: "scatter", 
                            data: value
                        });
                    });
                    myChart.resize();
                    myChart.hideLoading();
                    myChart.setOption(option); 
                }
            });
        };

        if(chart_type === "2") {
            load_line_chart();
        } else if (chart_type ==="3") {
            load_bar_chart();
        } else if (chart_type ==="5") {
            load_pie_chart();
        } else if (chart_type ==="4") {
            load_datatables();
        } else if (chart_type ==="8") {
            load_scatter_chart();
        }

    };
    $.fn.load_chart.defaults = {
    };
})(jQuery);
